package com.egao.common.module.push.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.component.elasticsearch.entity.vo.ElasticPushMsgFormVO;
import com.egao.common.component.elasticsearch.service.ElasticSearchService;
import com.egao.common.component.elasticsearch.service.ElasticStatisticsService;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.company.constants.CheckRecordConstants;
import com.egao.common.module.company.entity.Preach;
import com.egao.common.module.company.entity.PreachCloud;
import com.egao.common.module.company.entity.Recruit;
import com.egao.common.module.company.mapper.PreachCloudMapper;
import com.egao.common.module.company.mapper.PreachMapper;
import com.egao.common.module.company.mapper.RecruitMapper;
import com.egao.common.module.push.constants.PushConstants;
import com.egao.common.module.push.entity.AbilityFormDTO;
import com.egao.common.module.push.mapper.PositionMatchingMapper;
import com.egao.common.module.push.entity.PositionMatching;
import com.egao.common.module.push.service.PositionMatchingService;
import com.egao.common.module.push.service.PushMsgService;
import com.egao.common.module.system.constants.DictConstants;
import com.egao.common.module.system.entity.Dict;
import com.egao.common.module.system.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 职位匹配详情表(PositionMatching)表服务实现类
 *
 * @author dl
 * @since 2021-03-03 16:31:22
 */
@Service("positionMatchingService")
public class PositionMatchingServiceImpl extends ServiceImpl<PositionMatchingMapper, PositionMatching> implements PositionMatchingService {

    @Autowired
    private RecruitMapper recruitMapper;

    @Autowired
    private PreachMapper preachMapper;

    @Autowired
    private PreachCloudMapper preachCloudMapper;

    @Autowired
    private ElasticStatisticsService elasticStatisticsService;

    @Autowired
    private DictService dictService;

    @Override
    public void savePositionMatching(List<PositionMatching> positionMatchingList, Integer businessId, String businessType, AbilityFormDTO abilityFormDTO) {
        PositionMatching pm = getAbility(abilityFormDTO);
        if (positionMatchingList != null && positionMatchingList.size() > 0) {
            for (PositionMatching positionMatching : positionMatchingList) {
                positionMatching.setBusinessId(businessId);
                positionMatching.setType(businessType);
                BeanUtil.copyProperties(pm, positionMatching, CopyOptions.create().setIgnoreNullValue(true));
            }
            saveBatch(positionMatchingList);
        }
    }

    @Override
    public JsonResult getTotal(Integer businessId, String businessType) throws IOException {
        Map<String, Object> map = new HashMap<>(16);
        List<PositionMatching> list = baseMapper.selectList(new QueryWrapper<PositionMatching>().eq("business_id", businessId).eq("type", businessType));
        getPushContent(businessId, businessType, map);
        map.put("list", list);
        ElasticPushMsgFormVO ep = new ElasticPushMsgFormVO();
        ep.setType(businessType);
        ep.setBusinessId(businessId);
        map.put("pushCount", elasticStatisticsService.pushCountTotal(ep));
        map.put("pushReadCount", elasticStatisticsService.pushReadTotal(ep));
        map.put("pushResumeCount", elasticStatisticsService.pushResumeTotal(ep));
        return JsonResult.ok().setData(map);
    }

    /**
     * 获得推送状态描述
     *
     * @param businessId   业务编号
     * @param businessType 业务类型
     * @param map          业务类型
     * @return
     */
    private Map<String, Object> getPushContent(Integer businessId, String businessType, Map<String, Object> map) {
        String pushState = PushConstants.NO;
        String pushContent = "";
        if (CheckRecordConstants.CHECK_RECRUIT.equals(businessType)) {
            Recruit recruit = recruitMapper.selectById(businessId);
            if (recruit != null) {
                pushState = getState(recruit.getState(), recruit.getPushFlag());
                pushContent = getStateContent(recruit.getState(), recruit.getPushFlag());
            }
        }
        if (CheckRecordConstants.CHECK_PREACH.equals(businessType)) {
            Preach preach = preachMapper.selectById(businessId);
            if (preach != null) {
                pushState = getState(preach.getState(), preach.getPushFlag());
                pushContent = getStateContent(preach.getState(), preach.getPushFlag());
            }
        }
        if (CheckRecordConstants.CHECK_PREACH_CLOUD.equals(businessType)) {
            PreachCloud preachCloud = preachCloudMapper.selectById(businessId);
            if (preachCloud != null) {
                pushState = getState(preachCloud.getState(), preachCloud.getPushFlag());
                pushContent = getStateContent(preachCloud.getState(), preachCloud.getPushFlag());
            }
        }
        map.put("pushState", pushState);
        map.put("pushStateContent", pushContent);
        return map;
    }

    /**
     * 获取推送状态
     *
     * @param state    业务状态
     * @param pushFlag 单位是否推送
     * @return
     */
    private String getState(String state, String pushFlag) {
        // 未审核
        if (CheckRecordConstants.CHECKING.equals(state)) {
            return PushConstants.NO;
        }
        // 审核不通过
        if (CheckRecordConstants.CHECK_FAILED.equals(state)) {
            return PushConstants.NO;
        }
        // 单位不推送
        if (PushConstants.NO.equals(pushFlag)) {
            return PushConstants.NO;
        }
        return PushConstants.YES;
    }

    /**
     * 未推送原因
     *
     * @param pushFlag 单位是否推送
     * @return
     */
    private String getStateContent(String state, String pushFlag) {
        // 未审核
        if (CheckRecordConstants.CHECKING.equals(state)) {
            return PushConstants.PUSH_CONTENT_CHECKING;
        }
        // 审核不通过
        if (CheckRecordConstants.CHECK_FAILED.equals(state)) {
            return PushConstants.PUSH_CONTENT_FAILED;
        }
        // 单位不推送
        if (PushConstants.NO.equals(pushFlag)) {
            return PushConstants.PUSH_CONTENT;
        }
        return "";
    }

    private PositionMatching getAbility(AbilityFormDTO abilityFormDTO) {
        PositionMatching positionMatching = new PositionMatching();

        String state = "1";

        if (abilityFormDTO == null) {
            positionMatching.setAbility(state);
            return positionMatching;
        }

        if (abilityFormDTO.getZzmm() != null) {
            for (String item : abilityFormDTO.getZzmm()) {
                state = "0";
                String label = dictService.cacheLabel(DictConstants.TYPE_ZZMM, item);
                String old = positionMatching.getZzmm();
                positionMatching.setZzmm(!StrUtil.isBlank(old) ? old + "," + label : label);
            }
        }


        if (abilityFormDTO.getXl() != null) {
            for (String item : abilityFormDTO.getXl()) {
                state = "0";
                String label = dictService.cacheLabel(DictConstants.TYPE_XL, item);
                String old = positionMatching.getXl();
                positionMatching.setXl(!StrUtil.isBlank(old) ? old + "," + label : label);
            }
        }

        if (abilityFormDTO.getPractice() != null) {
            for (String item : abilityFormDTO.getPractice()) {
                state = "0";
                String old = positionMatching.getPractice();
                positionMatching.setPractice(!StrUtil.isBlank(old) ? old + "," + item : item);
            }
        }

        if (abilityFormDTO.getHonor() != null) {
            for (String item : abilityFormDTO.getHonor()) {
                state = "0";
                String old = positionMatching.getHonor();
                positionMatching.setHonor(!StrUtil.isBlank(old) ? old + "," + item : item);
            }
        }

        if (abilityFormDTO.getJob() != null) {
            for (String item : abilityFormDTO.getJob()) {
                state = "0";
                String old = positionMatching.getJob();
                positionMatching.setJob(!StrUtil.isBlank(old) ? old + "," + item : item);
            }
        }

        if (abilityFormDTO.getCertificate() != null) {
            for (String item : abilityFormDTO.getCertificate()) {
                state = "0";
                String[] arr = item.split(",");
                if (arr.length != 2) {
                    continue;
                }

                Dict dict = dictService.getByParent(DictConstants.ITEN_CERTIFICATE, 0, arr[0]);
                if (dict == null) {
                    continue;
                }

                Dict result = dictService.getByParent(DictConstants.ITEN_CERTIFICATE, dict.getId(), arr[1]);
                if (result == null) {
                    continue;
                }

                String old = positionMatching.getCertificate();
                positionMatching.setCertificate(!StrUtil.isBlank(old) ? old + "," + result.getLabel() : result.getLabel());
            }
        }


        positionMatching.setAbility(state);
        return positionMatching;
    }
}